package com.learning.android.currencyconvertor;


import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.Messenger;
import android.view.View;


public class CurrencyConvertor extends ListActivity {
	
    
	private CurrencyDBAdapter currDBAdapter;
	
	//Adapter for Currencies List View
	private CurrencyListAdapter currencyListAdapter;
	
	//Cursor for all the selected currencies
	private Cursor currencies;
	
	//New Thread to update currencies converter rates
	private HandlerThread handlerThread = new HandlerThread("handler_thread");
	
	//Messenger to receive incoming messages
	private Messenger uIMessenger;
	
	//Message Handler for download currency exchange rates
	private CurrencySyncHandler currSyncHandler;
	
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_currency_selected);
        
        currDBAdapter = new CurrencyDBAdapter(this);
        currDBAdapter.open();
        
        //Load currencies into list
        currencies = currDBAdapter.selectedCurrencies(CurrencyDBAdapter.SELECTION_MODE[0]);
        startManagingCursor(currencies);
        
        //Assign value for Currency ListAdapter
        currencyListAdapter = new CurrencyListAdapter(currencies,this,currDBAdapter);
        
        //Set Adapter 
        setListAdapter(currencyListAdapter);
         
        //Create a new Messenger to Receive message
        uIMessenger = new Messenger(new messageHandler());
        
        
       //Start New Thread Handler to Load Currencies
        handlerThread.start();
        currSyncHandler = new CurrencySyncHandler(handlerThread.getLooper(), this.getBaseContext(),currDBAdapter);
        startCurrencySync(CurrencyDBAdapter.SELECTION_MODE[0]);
         
    }
    


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//handlerThread.stop();
		currencyListAdapter.updateDBAsArrayList();
	}




	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		//handlerThread.start();
	}




	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//handlerThread.start();
	}




	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		currencyListAdapter.updateDBAsArrayList();
		//handlerThread.stop();
	}




	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		currencyListAdapter.updateDBAsArrayList();
		//handlerThread.stop();
	}




	private void startCurrencySync(int mode)  {
		// TODO Auto-generated method stub
         
        //Only Update Selected Only Currencies
         Message currencyUpdatedMessage = currSyncHandler.obtainMessage();
         Bundle msgData = new Bundle();
         msgData.putInt("Selection", mode);
         currencyUpdatedMessage.setData(msgData);
         currencyUpdatedMessage.replyTo = uIMessenger;
         
         //Update Database before sending Message
         currencyUpdatedMessage.sendToTarget();
	}



    
    private void currenceListViewUpdate()
    {
    	//currencies = currDBAdapter.selectedCurrencies(CurrencyDBAdapter.SELECTION_MODE[0]);
    	//Update Current Changes to Database
    	currencyListAdapter.updateDBAsArrayList();
    	//currencies.requery();
    	currencies = currDBAdapter.selectedCurrencies(CurrencyDBAdapter.SELECTION_MODE[0]);
    	currencyListAdapter.copyCursor2ArrayList(currencies);
    	currencyListAdapter.notifyDataSetChanged();
    	//currencies.moveToNext();
    	//System.out.println("Currency exchange Rate: " + currencies.getDouble(currencies.getColumnIndex(CurrencyDBAdapter.KEY_RATE_ADV)));

    }

    //Add Currency to the list view
	public void addCurrencyClick(View v)
    {
    	System.out.println("Add New Currency");
    	
    }
	
	class messageHandler extends Handler
	{
		@Override
		public void handleMessage(Message msg) {
			
			switch(msg.what)
			{
			//Only Selected Currencies to Update
			case CurrencySyncHandler.MSG_CURR_SELECT_UPD:
				System.out.println("Selected Currencies has been updated");
				currenceListViewUpdate();
				startCurrencySync(CurrencyDBAdapter.SELECTION_MODE[1]);
				break;
			case CurrencySyncHandler.MSG_CURR_ALL_UPD:
				System.out.println("All currencies has been updated");
				currenceListViewUpdate();
				//startCurrencySync(CurrencyDBAdapter.SELECTION_MODE[0]);
				break;
			default:
				super.handleMessage(msg);
			}
		}
	}
	
	public void messageSend () 
	{
	    try{	
		uIMessenger.send(Message.obtain(null,CurrencySyncHandler.MSG_CURR_SELECT_UPD , 0, 0));
	    }
	    catch(Exception e)
	    {
	    	System.out.println("Exception for Sending Message for " + e.toString());
	    }
	}
	
}